package com.sali.application.sysrole.service.impl;

import com.sali.application.sysrole.model.vo.SysRolesMenuApisVO;
import com.sali.application.sysrole.service.ISysRolesService;
import com.sali.application.sysuser.contants.SysUserContants;
import com.sali.rbac.model.SysApisModel;
import com.sali.rbac.model.SysMenusModel;
import com.sali.rbac.repository.ISysApisRepository;
import com.sali.rbac.repository.ISysMenusRepository;
import com.sali.redis.util.RedisUtil;
import com.sali.utils.methods.JsonUtil;
import com.sali.utils.methods.jwt.JwtUtil;
import com.sali.utils.threadlocal.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: sali
 * @date: 2024/8/24 下午12:24.
 * @version: 1.0
 */
@Service
public class SysRolesServiceImpl implements ISysRolesService {

    @Autowired
    private ISysMenusRepository sysMenusRepository;

    @Autowired
    private ISysApisRepository sysApisRepository;

    @Resource
    private RedisUtil<String> redisUtil;

    @Override
    public SysRolesMenuApisVO findRoleMenusPermission(Long roleId) {
        List<SysMenusModel> menuList = sysMenusRepository.findSysMenusList(roleId);
        List<SysApisModel> apisList = sysApisRepository.findRoleApis(roleId);
        SysRolesMenuApisVO vo = new SysRolesMenuApisVO();
        if (CollectionUtils.isEmpty(menuList)) {
            menuList = new ArrayList<>();
        }
        if (CollectionUtils.isEmpty(apisList)) {
            apisList = new ArrayList<>();
        }
        vo.setMenus(menuList);
        vo.setPermissions(apisList);
        // 把当前角色对应的权限放入到redis，方便后续的拦截器进行控制和使用
        redisUtil.set(SysUserContants.RBAC_PERMISSION_LIST + UserThreadLocal.get().getId(), JsonUtil.obj2String(apisList), JwtUtil.EXPIRE_TIME, TimeUnit.MILLISECONDS);
        return vo;
    }
}
